"""实验数据的记录与保存"""
import csv
import datetime
from pathlib import Path


class DataRecorder:
    def __init__(self):
        # 初始化数据容器
        self.cursor_data = []  # 光标/目标/解码数据
        self.joystick_data = []  # 摇杆数据
        self.trial_log = {
            "N": [], "start": [], "end": [], "success": [], "target_index": []
        }
        self._init_log_folder()

    def _init_log_folder(self):
        """初始化日志文件夹"""
        self.folder_path = Path("log_folder")
        try:
            self.folder_path.mkdir(exist_ok=True)
        except Exception as e:
            print(f"日志文件夹创建失败: {e}")

    def record_cursor_data(self, joystick_pos, cursor_pos, target_pos, score, threshold):
        """记录光标相关实时数据"""
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
        self.cursor_data.append([
            timestamp, joystick_pos[0], joystick_pos[1],
            cursor_pos[0], cursor_pos[1],
            target_pos[0], target_pos[1],
            score, threshold
        ])

    def record_trial_status(self, trial_num, start_time, end_time, target_idx, success):
        """记录单次试验的状态"""
        # print("record_trial_status:", trial_num, start_time, end_time, target_idx, success)
        self.trial_log["N"].append(trial_num)
        self.trial_log["start"].append(start_time)
        self.trial_log["end"].append(end_time)
        self.trial_log["target_index"].append(target_idx)
        self.trial_log["success"].append(success)

    def save_all_data(self, joystick_raw_data):
        """保存所有数据到CSV文件"""
        current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        self._save_cursor_data(current_time)
        self._save_joystick_data(current_time, joystick_raw_data)
        self._save_trial_log(current_time)

    def _save_cursor_data(self, timestamp):
        """保存光标相关数据"""
        filename = self.folder_path / f"cursor_data_{timestamp}.csv"
        with open(filename, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                "Timestamp", "Joystick_X", "Joystick_Y",
                "Cursor_X", "Cursor_Y", "Target_X", "Target_Y",
                "Decoded_Score", "Score_Threshold"
            ])
            writer.writerows(self.cursor_data)

    def _save_joystick_data(self, timestamp, raw_data):
        """保存摇杆原始数据"""
        filename = self.folder_path / f"joystick_data_{timestamp}.csv"
        with open(filename, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Timestamp", "Joystick_X", "Joystick_Y"])
            writer.writerows(raw_data[1:])  # 跳过表头

    def _save_trial_log(self, timestamp):
        """保存试验日志"""
        filename = self.folder_path / f"trial_log_{timestamp}.csv"
        with open(filename, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(["Num", "Start_time", "End_time", "Target_label", "Success"])
            # 整合日志数据
            log_data = zip(
                self.trial_log["N"],
                self.trial_log["start"],
                self.trial_log["end"],
                self.trial_log["target_index"],
                self.trial_log["success"]
            )
            writer.writerows(log_data)
